package com.sdgakj.service.user;

import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumUserType;
import com.sdgakj.repository.UserDao;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.account.AccountService;
import com.sdgakj.service.login.UserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class UserService {
   
	private static Logger logger =LoggerFactory.getLogger(UserLoginService.class);

	@Autowired
	private UserDao userDao;

	@Autowired
	private AccountService accountService;
	
	/**
	 * 根据电话查找用户
	 * @param tell 电话
	 * @return
	 */
	public User getUserByTell(String tell) {
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		//如果电话不为空的话，按照其对应的登录账号查询
		if(!StringUtils.isEmpty(tell)){
			filters.put("mobile", new SearchFilter("mobile",Operator.EQ,tell));
		}
		
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findOne(spec);
	}


	/**
	 * 通过手机号
	 *
	 * */

	public User getUserByMobile(String mobile){
		return userDao.findByMobile(mobile);
	}
	/**
	 * 根据tell和角色类型查找用户
	 * @param tell 电话===
	 * @return
	 */
	public User getUserByTell(String tell,String role) {
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		//如果电话不为空的话，按照其对应的登录账号查询
		if(!StringUtils.isEmpty(tell)){
			filters.put("loginName", new SearchFilter("loginName",Operator.EQ,tell));
			filters.put("type", new SearchFilter("type",Operator.EQ,role));
		}
		
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findOne(spec);
	}
	
	/**
	 * 根据mobile和角色类型查找admin类型用户
	 * @param tell 电话===
	 * @return
	 */
	public User getAdminByTell(String tell,String role) {
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		//如果电话不为空的话，按照其对应的登录账号查询
		if(!StringUtils.isEmpty(tell)){
			filters.put("mobile", new SearchFilter("mobile",Operator.EQ,tell));
			filters.put("type", new SearchFilter("type",Operator.EQ,role));
			filters.put("deltag", new SearchFilter("deltag",Operator.EQ, EnumIsDelete.NOTDELETE.getCode()));
		}
		
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findOne(spec);
	}
	
	public List<User> getAdminByMobile(String tell,String role){
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		//如果电话不为空的话，按照其对应的登录账号查询
		if(!StringUtils.isEmpty(tell)){
			filters.put("mobile", new SearchFilter("mobile",Operator.EQ,tell));
			filters.put("type", new SearchFilter("type",Operator.EQ,role));
			filters.put("deltag", new SearchFilter("deltag",Operator.EQ, EnumIsDelete.NOTDELETE.getCode()));
		}
		
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findAll(spec);
	}
	
	/**
	 * 根据用户的手机和id查询管理员
	 * @param mobile
	 * @param userId
	 * @return
	 */
	public User getUserByMobileAndUserId(String mobile,Long userId){
		
		return userDao.findByMobileAndUserId(mobile, userId);
	}
	/**
	 * 根据用户id查询用户
	 * @param userId  用户id
	 * @return
	 */
	public User getUserById(Long userId){
		return userDao.findOne(userId);
	}
	
	/**
	 * 查找用户名为电话的User
	 * @return
	 */
	public User getUserByLoginName(String loginName) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		// 如果schoolId不为0，则按照对应用户的驾校id查询其学员
		if (!StringUtils.isEmpty(loginName)) {
			filters.put("loginName", new SearchFilter("loginName", Operator.EQ, loginName));
		}
		Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(), User.class);

		return userDao.findOne(spec);
	}


	/*getfamilyfamouspById


	*/
	public Page<User> getfamilyfamouspById(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortName,
									  String sortType) {
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, Sort.Direction.DESC, "id");

		// Specification<Truck> spec = buildSpecification(searchParams);
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findAll(spec, pageRequest);

	}
	/**
	 * 查找用户名为电话的User
	 * @return
	 */
	public User getUserByLoginName(String loginName,String role) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		// 如果schoolId不为0，则按照对应用户的驾校id查询其学员
		if (!StringUtils.isEmpty(loginName)) {
			filters.put("loginName", new SearchFilter("loginName", Operator.EQ, loginName));
			filters.put("type", new SearchFilter("type", Operator.EQ, role));
			//filters.put("appType", new SearchFilter("appType",Operator.EQ,"0")); // app用户类型默认为0
		}
		Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(), User.class);

		return userDao.findOne(spec);
	}
	
	/**
	 * 更新用户信息
	 * @param entity
	 */
	public void updateUser(User entity) {
		userDao.save(entity);
	}

	/**
	 * 重置管理员密码
	 * @param tell
	 * @param pwd
	 * @param insertCode
	 * @return
	 */
	public void recoverAdminPwd(String tell, String pwd, String insertCode) {
		try {
			User user = this.getUserByTell(tell, EnumUserType.ADMIN.getCode());
			user.setMobile(tell);
			user.setPlainPassword(pwd);
			accountService.entryptPassword(user);
			this.updateUser(user);
		} catch (ServiceException e) {
			logger.error("重置管理员密码失败："+e.getMessage());
		}
	}
	

	/**
	 * 修改管理员密码
	 * @param pwd
	 * @return
	 */
	public void changeAdminPwd(Long id, String pwd) {
		try {
			User user = this.getUserById(id);
			user.setPlainPassword(pwd);
			accountService.entryptPassword(user);
			this.updateUser(user);
		} catch (ServiceException e) {
			logger.error("修改管理员密码失败："+e.getMessage());
		}
	}
	/**
	 * 添加管理员用户
	 */
	public Long saveUser(User user){
		accountService.entryptPassword(user);
		User u=userDao.save(user);
		return u.getId();
	}
	
	/**
	 * 删除用户--只更新用户状态
	 * @param entity
	 */
	public void deleteUser(User entity){
		userDao.save(entity);
	}
	
	/**
	 * 根据用户类型查询用户列表
	 * @return
	 */
	public Page<User> getUsers(String userType,Map<String,Object> searchParams,int pageNumber,int pageSize,
								String sortType) {
		PageRequest pageRequest =buildPageRequest(pageNumber,pageSize,sortType);
		Specification<User> spec =buildSpecification(userType,searchParams);
		
		return userDao.findAll(spec,pageRequest);
	}
	
	/***
	 * 查询所有的招商人员
	 * @return
	 */
	public List<User> getBusinessRoleUser(){
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		filters.put("role.rolename", new SearchFilter("role.rolename",Operator.LIKE, EnumUserType.ASSIGNUSER.getName()));
		filters.put("deltag", new SearchFilter("deltag",Operator.EQ, EnumIsDelete.NOTDELETE.getCode()));
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findAll(spec);
	}
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}
	
	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<User> buildSpecification(String userType,Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		//  根据用户类型设置查询条件
		filters.put("type", new SearchFilter("type", Operator.EQ, userType));
		Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(),User.class);
		return spec;
	}


    /**
     * 查找用户
     * @param loginName
     * @param password
     * @param mobile
     * @param type
     * @return
     */
    public User findUser(String loginName, String password, String mobile, int type) {

        //   Map<String,Object> searchParams = new HashMap<>();
        //   Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        User user;
        if(!StringUtils.isEmpty(loginName)){
            user = userDao.findByLoginName(loginName);
        }else{

        }

        return null;
    }
    
    
	public List<User> getUserByName(String name) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if(!StringUtils.isEmpty(name)){
			filters.put("name", new SearchFilter("name", Operator.LIKE, name));
		}
		Specification<User> spec = DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findAll(spec);
	}

	/**
	 * 根据设备号查询注册数
	 * @return
	 */
	public List<User> getUersByUDID(String devicenumber){
		Map<String,Object> searchParams =new HashMap<String,Object>();
		Map<String,SearchFilter>  filters =SearchFilter.parse(searchParams);
		//如果电话不为空的话，按照其对应的登录账号查询
		filters.put("udid", new SearchFilter("udid",Operator.EQ,devicenumber));
		
		Specification<User> spec =DynamicSpecifications.bySearchFilter(filters.values(), User.class);
		return userDao.findAll(spec);
	}

	public List<User> getPointOredrByUserId() {
		return userDao.getPointOredrByUserId();
	}
}
